package com.ltd.fragmentdemo.activities;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;

import com.ltd.fragmentdemo.R;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class WelcomeActivity extends AppCompatActivity {
    private boolean isFirst = false;//是否第一次打开App


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_welcome);
        initData();
    }

    private void initData() {
        Observable.create(new ObservableOnSubscribe<Intent>() {
            @Override
            public void subscribe(ObservableEmitter<Intent> e) throws Exception {
                Intent intent;
                SharedPreferences sp = getSharedPreferences("WelcomeActivity", 0);
                isFirst = sp.getBoolean("isFirst", true);
                if (isFirst) {
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putBoolean("isFirst", false);
                    editor.commit();
                    intent = new Intent(WelcomeActivity.this, StartActivity.class);
                } else {
                    intent = new Intent(WelcomeActivity.this, MainActivity.class);
                }
                Thread.sleep(2000);
                e.onNext(intent);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Intent>() {
                    @Override
                    public void accept(Intent intent) throws Exception {
                        startActivity(intent);
                        finish();
                    }
                });
    }
}
